import 'package:azlistview/azlistview.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_boost/boost_navigator.dart';
import 'package:flutter_boost/flutter_boost.dart';
import 'package:hzcloud_flt/models/common/index.dart';
import 'package:hzcloud_flt/models/common/models.dart';
import 'package:hzcloud_flt/models/common/utils.dart';
import 'package:shimmer/shimmer.dart';

const String headerIndexTitle = "★";

class SwitchParkPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return _SwitchParkPageState();
  }
}

class _SwitchParkPageState extends State<SwitchParkPage>
    with PageVisibilityObserver {
  List<ContactInfo> contactList = [];

  double susItemHeight = 45;

  @override
  void onPageShow() {
    // TODO: implement onPageShow
    super.onPageShow();
  }

  @override
  void onPageHide() {
    // TODO: implement onPageHide
    super.onPageHide();
  }

  @override
  void onForeground() {
    // TODO: implement onForeground
    super.onForeground();
  }

  @override
  void onBackground() {
    // TODO: implement onBackground
    super.onBackground();
  }

  @override
  void initState() {
    super.initState();
    loadData();
  }

  void loadData() async {
    rootBundle.loadString('assets/data/car_models.json').then((value) {
      List list = json.decode(value);
      list.forEach((v) {
        contactList.add(ContactInfo.fromJson(v));
      });
//      contactList = contactList.reversed.toList();
//      log('$contactList');
      _handleList(contactList);
    });
  }

  void _handleList(List<ContactInfo> list) {
    if (list.isEmpty) return;
    for (int i = 0, length = list.length; i < length; i++) {
      String pinyin = PinyinHelper.getPinyinE(list[i].name);
      String tag = pinyin.substring(0, 1).toUpperCase();
      list[i].namePinyin = pinyin;
      if (RegExp("[A-Z]").hasMatch(tag)) {
        list[i].tagIndex = tag;
      } else {
        list[i].tagIndex = "#";
      }
    }
    // A-Z sort.
    SuspensionUtil.sortListBySuspensionTag(contactList);

    // show sus tag.
    SuspensionUtil.setShowSuspensionStatus(contactList);

    // add header.
    contactList.insert(
        0, ContactInfo(name: 'header', tagIndex: headerIndexTitle));

    setState(() {});
  }

  Widget customHeader() {
    return Column(
      children: <Widget>[
        Container(
          color: Colors.white,
          padding: EdgeInsets.only(left: 32, top: 20, right: 32, bottom: 16),
          child: Image.asset(
            Utils.getImgPath('ic_car_models_header1'),
            fit: BoxFit.contain,
          ),
        ),
        Container(
          color: Colors.white,
          padding: EdgeInsets.only(left: 32, top: 0, right: 32, bottom: 16),
          child: Image.asset(
            Utils.getImgPath('ic_car_models_header2'),
            fit: BoxFit.contain,
          ),
        ),
      ],
    );
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Scaffold(
      backgroundColor: Color(0xFFF2F2F2),
      appBar: AppBar(
        title: Text('切换物业区域'),
        leading: IconButton(
          onPressed: () {
            BoostNavigator.instance.pop();
          },
          icon: Icon(Icons.backpack),
        ),
      ),
      body: AzListView(
        data: contactList,
        itemCount: contactList.length,
        itemBuilder: (BuildContext context, int index) {
          if (index == 0) return customHeader();
          ContactInfo model = contactList[index];
          return ParkItem();
        },
        susItemHeight: susItemHeight,
        susItemBuilder: (BuildContext context, int index) {
          ContactInfo model = contactList[index];
          if (headerIndexTitle == model.getSuspensionTag()) {
            return Container();
          }
          return ParkHeaderItem(
              context: context, tag: model.getSuspensionTag());
        },
        indexBarData: [headerIndexTitle, ...kIndexBarData],
        indexBarOptions: IndexBarOptions(
          needRebuild: true,
          selectTextStyle: TextStyle(
              fontSize: 12, color: Colors.white, fontWeight: FontWeight.w500),
          selectItemDecoration:
              BoxDecoration(shape: BoxShape.circle, color: Colors.blue),
          indexHintWidth: 96,
          indexHintHeight: 97,
          indexHintDecoration: BoxDecoration(
            image: DecorationImage(
              image: AssetImage(Utils.getImgPath('ic_index_bar_bubble_white')),
              fit: BoxFit.contain,
            ),
          ),
          indexHintAlignment: Alignment.centerRight,
          indexHintTextStyle: TextStyle(fontSize: 24.0, color: Colors.blue),
          indexHintOffset: Offset(-30, 0),
        ),
      ),
    );
  }
}

class ParkItem extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return GestureDetector(
      onTap: () {},
      child: Container(
        constraints: BoxConstraints(minHeight: 80),
        decoration: BoxDecoration(
            color: Colors.white, borderRadius: BorderRadius.circular(10)),
        margin: EdgeInsets.only(left: 15, right: 35, bottom: 15),
        padding: EdgeInsets.symmetric(horizontal: 10, vertical: 10),
        child: Row(
          mainAxisSize: MainAxisSize.max,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            CachedNetworkImage(
              width: 80,
              height: 80,
              imageUrl: 'imageUrl',
              placeholder: (context, url) =>
                  Image.asset('assets/images/park.png'),
              errorWidget: (context, url, error) =>
                  Image.asset('assets/images/park.png'),
              fit: BoxFit.fill,
            ),
            Expanded(
              child: Padding(
                padding: EdgeInsets.only(left: 10),
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      '日照测试物业区域',
                      style: TextStyle(
                        fontSize: 16,
                        fontWeight: FontWeight.w500,
                        color: Color(0xFF333333),
                      ),
                    ),
                    Text(
                      '山东路638号山东路638号山东路638号山东路',
                      style: TextStyle(
                        fontSize: 14,
                        color: Color(0xFF999999),
                      ),
                    ),
                    Container(
                      padding: EdgeInsets.symmetric(vertical: 0, horizontal: 2),
                      decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(3),
                        border:
                            Border.all(color: Color(0xFF999999), width: 0.5),
                      ),
                      child: Text(
                        '77856',
                        textAlign: TextAlign.center,
                        style: TextStyle(
                          fontSize: 13,
                          color: Color(0xFF999999),
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ),
            Container(
              color: Colors.red,
              alignment: Alignment.topCenter,
              child: Image.asset('assets/images/next_arrow.png'),
            ),
          ],
        ),
      ),
    );
  }
}

class ParkHeaderItem extends StatelessWidget {
  final BuildContext context;
  final String tag;

  const ParkHeaderItem({Key key, this.context, this.tag}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    String showTag = tag;
    if (showTag == '★') {
      showTag = '★ 热门城市';
    }
    return Container(
      height: 45,
      width: MediaQuery.of(context).size.width,
      padding: EdgeInsets.only(left: 16.0),
      color: Color(0xFFF2F2F2),
      alignment: Alignment.centerLeft,
      child: Text(
        '$showTag',
        softWrap: false,
        style: TextStyle(
          fontSize: 14.0,
          fontWeight: FontWeight.w600,
          color: Color(0xFF666666),
        ),
      ),
    );
  }
}
